var w,h,className,tableOffsetTop;
var userId, userDepartment, workMattersId, eightFieldsId, workMattersTableIndex, roleId;
var eightFieldsIds = [];//作为存储提交工单关联的eightFieldsId组
var config;//表格的配置文件

function getSrceenWH(){
    w = $(window).width();
    h = $(window).height();
    $('#dialogBg').width(w).height(h);
    tableOffsetTop = $('.c');
}

window.onresize = function(){
    getSrceenWH();
}
$(window).resize();

function setUserId() {
    //从cookie中取出userId
    var cookieStr = document.cookie.toString();
    var index = cookieStr.indexOf('userId');
    userId = cookieStr.substr(index).split("=")[1].split(';')[0];
    //从cookie中取出userDepartment
    var index2 = cookieStr.indexOf('userDepartment');
    userDepartment = cookieStr.substr(index2).split('=')[1].split(';')[0];
    //从cookie中取出roleId
    var index3 = cookieStr.indexOf('roleId');
    roleId = cookieStr.substr(index3).split('=')[1].split(';')[0];
}

function setWorkMattersId(clickIndex) {
    workMattersId = clickIndex;//设置当前工作事项id
    workMattersTableIndex = '#infoTable' + workMattersId.toString();//设置当前工作事项下的表格id，以确定当前显示的是哪一个页面
}

function addDataToCompareItemsTable(data) {
    var $tbody = $(workMattersTableIndex + ' .compareItemsTable tbody');
    $tbody.find('tr').remove();//先删除前一次添加的对照事项
        for (var i = 0; i < data.length; i++) {
            var $tr = $('<tr></tr>');
            var $td = $('<td></td>');
        $td.append(data[i].compareItem);
        $tr.append($td);
        $tr.data("eightFieldsId", data[i].id);//对照事项查出来后，通过设置自定义属性data-eightFieldsId存储即eightFieldsId，方便后续查找
        $tbody.append($tr);
    }
    //选择对照事项
    $tbody.find('tr').click(function () {
        $tbody.find('tr').removeClass('trSelected');
        $(this).addClass('trSelected');
    });
}

function addDataToSelectedTable(data) {
    var $tbody = $(workMattersTableIndex + ' .selectedTable tbody');
    var $tr = $('<tr></tr>');
    var $td = $('<td></td>');
    $td.append(data.concatStr);
    $tr.append($td);
    $tr.data('selectedEightFieldsId', data.selectedEightFieldsId);
    $tbody.append($tr);

    //点击已选择框的效果
    $tbody.find('tr').click(function () {
        $tbody.find('tr').removeClass('trSelected');
        $(this).addClass('trSelected');
        $(workMattersTableIndex + ' .eightFieldsCancel').removeAttr("disabled");
    });
}

//清空新增表单窗口中的数据
function emptyTheForm() {
    $(workMattersTableIndex + ' .selectedTable tbody').find('tr').remove();
    $(workMattersTableIndex + ' .compareItemsTable tbody').find('tr').remove();
    $(workMattersTableIndex + ' .selfcheckproblem').val('');
    $(workMattersTableIndex + ' .measures').val('');
    $(workMattersTableIndex + ' .finish_result').val('');
    $(workMattersTableIndex + ' .fourforms').val('');
    $(workMattersTableIndex + ' .diseducation').val('');
    $(workMattersTableIndex + ' .fileUploader .uploader input[type=file]').val('');
    eightFieldsIds.splice(0, eightFieldsIds.length);
}

//初始化工单详情页面
function initJsgridDialog(data) {
    //先清空里面的内容
    eightFieldsIds.splice(0);
    $(workMattersTableIndex + ' .jsgridBox .selectedTable-jsgrid tbody').find('tr').remove();
    $(workMattersTableIndex + ' .jsgridBox .selfcheckproblem').val('');
    $(workMattersTableIndex + ' .jsgridBox .measures').val('');
    $(workMattersTableIndex + ' .jsgridBox .finish_result').val('');
    $(workMattersTableIndex + ' .jsgridBox .fourforms').val('');
    $(workMattersTableIndex + ' .jsgridBox .diseducation').val('');
    $(workMattersTableIndex + ' .jsgridBox .fileUploader-jsgrid .uploader input[type=text]').val('');
    //获取当前工单关联的八项领域和对照信息
    var eightFieldIds = data.eightfields;
    addDataToJsgridDialogSelectedTable(eightFieldIds);
    $(workMattersTableIndex + ' .jsgridBox .selfcheckproblem').val(data.problem);
    $(workMattersTableIndex + ' .jsgridBox .measures').val(data.measures);
    $(workMattersTableIndex + ' .jsgridBox .finish_result').val(data.finish);
    $(workMattersTableIndex + ' .jsgridBox .fourforms').val(data.fourforms);
    $(workMattersTableIndex + ' .jsgridBox .diseducation').val(data.diseducation);
    $(workMattersTableIndex + ' .jsgridBox .fileDownloader-jsgrid .filename').val(data.userId + '_' + data.id);

    //判断当前点击的工单是否与当前登录用户属于同一部门，如果不属于则隐藏部分信息
    if (data.userDepartment != userDepartment) {
        debugger;
        $(workMattersTableIndex + ' .jsgridBox .fourforms').parent('div').hide();
        $(workMattersTableIndex + ' .jsgridBox .fileDownloader-jsgrid').hide();
    } else {
        $(workMattersTableIndex + ' .jsgridBox .fourforms').parent('div').show();
        $(workMattersTableIndex + ' .jsgridBox .fileDownloader-jsgrid').show();
    }
}

/*
* 将八大领域和对照事项添加到展示页面
* */
function addDataToJsgridDialogSelectedTable(data) {
    for (var i = 0; i < data.length; i++) {
        var selectedEightFieldsId = data[i].id;
        var eightFieldStr = data[i].eightFieldsContent;
        var compareItemStr = data[i].compareItem;
        var concatStr = '';
        if (!eightFieldsIds.includes(selectedEightFieldsId)) {
            eightFieldsIds.push(selectedEightFieldsId);
            concatStr = eightFieldStr.toString() + '<span>>>></span>' + compareItemStr.toString();//合并字段
            var $tbody = $(workMattersTableIndex + ' .selectedTable-jsgrid tbody');
            var $tr = $('<tr></tr>');
            var $td = $('<td></td>');
            $td.append(concatStr);
            $tr.append($td);
            $tr.data('selectedEightFieldsId', selectedEightFieldsId);
            $tbody.append($tr);

            //点击已选择框的效果
            $tbody.find('tr').click(function () {
                $tbody.find('tr').removeClass('trSelected');
                $(this).addClass('trSelected');
                $(workMattersTableIndex + ' .eightFieldsCancel-jsgrid').removeAttr("disabled");
            });
        }
    }
}

/*
* 删除工单
* */
function deleteSelfexamination(data) {
    $.ajax({
        url: mmssm_url + "selfexamination/delete",
        type: "POST",
        data: 'userId_selfExaminationId=' + userId + '_' + data.id,
        success: function (successdata) {
            if (successdata != -1) {
                resultDialog(true, workMattersTableIndex + ' .simpleDialog.default', function () {
                    $(workMattersTableIndex + ' .jsgrid').jsGrid("render");//删除后刷新表格
                });
            } else {
                resultDialog(false, workMattersTableIndex + ' .simpleDialog.default', function () {});
            }
        },
        error: function (error) {
            resultDialog(false, workMattersTableIndex + ' .simpleDialog.default', function () {});
        }
    });
}
//此方法处理table查询到的数据，将八大领域和对照事项的对应关系编号转换成文本
function resolveTableData(data) {
    var newProperty = [];
    for (var i = 0; i < data.length; i++) {
        var temp = data[i].eightfields;
        for (var j = 0; j < temp.length; j++) {
            //先判断原来的数组中有没有同样的元素，有的话就不重复添加（因为eightFieldsContent会重复）
            var content = temp[j].eightFieldsContent;
            //这里用indexOf也可以，不过返回的是对应数组元素的下标值
            if (!newProperty.includes(content)) {
                newProperty.push(content);
            }
        }
        data[i].eights = newProperty.join(',');//数组转换成字符串填回表格的data中
        newProperty.splice(0);//清空临时数组，准备下一个循环
    }
    return data;
}

$(function () {
    setUserId();//设置用户id
    getSrceenWH();

    //修改
    $('.btn-mod').click(function(){
        getRowData();
        className = $(this).attr('class');
        className = className.toString().substr(className.toString().indexOf('btn-hover'));
        $(workMattersTableIndex + ' #dialogBg').fadeIn(300);
        $(workMattersTableIndex + ' #dialog').removeAttr('class').addClass('animated '+className+'').fadeIn();
    });

    //删除
    $('.btn-del').click(function(){
        className = $(this).attr('class');
        className = className.toString().substr(className.toString().indexOf('btn-hover'));
        $(workMattersTableIndex + ' #dialogBg').fadeIn(300);
        $(workMattersTableIndex + ' .dialogDel #dialog').removeAttr('class').addClass('animated '+className+'').fadeIn();
    });

    $(".important.cl li").click(function (event) {
            $('.important li').removeClass('liSelected');
            $(this).addClass('liSelected');
            var clickIndex = $(this).data('index');//获取data-index值
            setWorkMattersId(clickIndex);//设置工作事项id
       var indexItem = '.contents .index[data-content=' + '"' + clickIndex + '"' + ']';
       var $test = $(indexItem);
       $test.find('i').css('left', $(this).offset().left + $(this).outerWidth() / 2 - 10);//将小三角块移动到点击的li的位置下方，这里获取的是点击元素相对于父元素的位置，再加上点击元素一半的长度，以居中
       $('.contents .index').not($test).css('display', 'none');//隐藏其他工作事项的页面
        $test.animate({height: 'toggle'}, 500, function () {//当前工作事项页面展开效果
            initDialog(workMattersTableIndex + ' .btn-add', workMattersTableIndex + ' .simpleDialog.addDialog', function () {

            });
           //jsgrid组件的js，当点击当前页面的时候再加载表格的数据
            config = {
                width: "100%",
                height: "400px",
                filtering: false,
                inserting: false,
                editing: false,
                sorting: true,
                paging: false,
                pageLoading: false,
                pageSize: 8,
                autoload: true,
                deleteConfirm: "确认需要删除数据？",
                loadMessage: "正在装载数据，请稍候......",
                noDataContent: "找不到数据，请重试",
                rowClick: function (rowData) {       //点击某行数据触发该方法
                    initJsgridDialog(rowData.item);
                    openDialog(workMattersTableIndex + ' .simpleDialog.showDialog', function () {
                    });
                },
                // data: clients,
                controller: {
                    loadData: function() {
                        var d = $.Deferred();

                        $.ajax({
                            type: "post",
                            url: "http://localhost:8080/mm-ssm/selfexamination/userid2",
                            dataType: "json",
                            data: {
                                userId: userId
                            },
                        }).done(function(response) {
                            response = resolveTableData(response);
                            d.resolve(response);
                        }).fail(function () {
                            console.log("Table can't get data.");
                        });
                        return d.promise();
                    },
                    deleteItem: function (rowData) {

                    },

                },
                confirmDeleting: false,
                onItemDeleting: function (args) {
                    args.cancel = true;//在这里阻止调用默认的删除方法，弹出自定义删除对话框，
                    openDefaultDialog(workMattersTableIndex + ' .simpleDialog.default', function () {
                        deleteSelfexamination(args.item);
                    }, function () {
                    });
                },
                fields: [
                    { name: 'id', title: '工单号', type: 'number', width: 5},
                    { name: "problem", title: "自查发现问题", type: "text", width: 50,
                        itemTemplate: function(value) {
                            return $("<div>").addClass("jsGridResizableDiv").text(value);
                        }
                    },
                    { name: "measures", title: "落实整改措施", type: "text", width: 50,
                        itemTemplate: function(value) {
                            return $("<div>").addClass("jsGridResizableDiv").text(value);
                        }
                    },
                    { name: "finish", title: "整改完成情况", type: "text", width: 50,
                        itemTemplate: function(value) {
                            return $("<div>").addClass("jsGridResizableDiv").text(value);
                        }
                    },
                    { name: "eights", title: "八大重点工作关联情况", type: "text", width: 80,
                        itemTemplate: function(value) {
                            return $("<div>").addClass("jsGridResizableDiv").text(value);
                        }
                    },
                    { name: "userName", title: "责任人", type: "text", width: 20 },
                    { name: "userDomain", title: "责任领域", type: "text", width: 20 },
                    { name: "userDepartment", title: "责任部门", type: "text", width: 20},
                    { name: "userPhone", title: "联系电话", type: "text", width: 30 },
                    {
                        type: 'control',
                        deleteButton: true,
                        editButton: false,
                        width: 5,
                    }
                ],
            };
           $(workMattersTableIndex + ' .jsgrid').jsGrid(config);
       });
    });

    $('.btn-more').click(function () {
        $(workMattersTableIndex + ' .moreBtnDiv').animate({height: 'toggle'}, 200);
    });

    //选择八大领域
    $('.eightFieldsTable tbody tr').click(function () {
        $(workMattersTableIndex + ' .eightFieldsTable tbody tr').removeClass('trSelected');
        eightFieldsId = $(this).find('td').data('index');//获取八大领域对应的id
        $(this).addClass('trSelected');

        //通过eightFieldsIndex、workMattersId查询出对应的对照事项（即compareitem）
        $.ajax({
            url: "http://localhost:8080/mm-ssm/eightfield/all",
            type: "POST",
            dataType: "JSON",
            data: {
                eightFieldsIndex: eightFieldsId,
                workMattersId: workMattersId
            },
            success: function (data) {
                addDataToCompareItemsTable(data);
            },
            error: function (error) {
                alert("Can't get compareitem.");
            }
        });
    });

    //添加八项规定+对照事项
    $('.eightFieldsAdd').click(function (event) {
        event.preventDefault();
        var eightFieldStr = $(workMattersTableIndex + ' .eightFieldsTable tbody .trSelected td').text();
        var compareItemStr =  $(workMattersTableIndex + ' .compareItemsTable tbody .trSelected td').text();
        //如果选择为空，作出提示
        if (eightFieldStr == '') {
            alert('请选择八大领域');
            return;
        }  else if (compareItemStr == '') {
            alert('请选择对照事项');
            return;
        }
        var selectedEightFieldsId = $(workMattersTableIndex + ' .compareItemsTable tbody .trSelected').data('eightFieldsId');//取出自定义属性data-eightFieldsId（即eightFieldsId）
        var data = {};
        //判断是否重复添加
        if (!eightFieldsIds.includes(selectedEightFieldsId)) {
            eightFieldsIds.push(selectedEightFieldsId);
            var concatStr = eightFieldStr.toString() + '<span>>>></span>' + compareItemStr.toString();//合并字段
            data = {
                selectedEightFieldsId: selectedEightFieldsId,
                concatStr: concatStr
            }
            addDataToSelectedTable(data);//合并好的字段通过方法添加到已选择框
        } else {
            alert("请勿重复添加");
        }
        $(workMattersTableIndex + ' .eightFields .trSelected').removeClass('trSelected');//本次选择已完成，去除所有的选中样式
    });

    $('.eightFieldsCancel').click(function (event) {
        event.preventDefault();
        console.log(eightFieldsIds);
        var $selectedtr = $(workMattersTableIndex + " .selectedTable tbody .trSelected");
        var selectedEightFieldsId = $selectedtr.data('selectedEightFieldsId');
        $selectedtr.remove();
        eightFieldsIds.splice($.inArray(selectedEightFieldsId, eightFieldsIds), 1);//如果选中的id在数组中，则把它删除掉
        //如果已选择框已经没有数据，则将删除按钮设为不可用
        if (eightFieldsIds.length == 0) {
            $(workMattersTableIndex + ' .eightFieldsCancel').attr("disabled", 'disabled');
        }
        console.log(eightFieldsIds);
    });

    //新增工单按钮的实现
    $('.addSelfExamBtn').click(function (event) {
        event.preventDefault();
       var problem = $(workMattersTableIndex + ' .selfcheckproblem').val();
       var measures = $(workMattersTableIndex + ' .measures').val();
       var finish = $(workMattersTableIndex + ' .finish_result').val();
       var fourforms = $(workMattersTableIndex + ' .fourforms').val();
       var diseducation = $(workMattersTableIndex + ' .diseducation').val();
       var file = $(workMattersTableIndex + ' .fileUploader input[type=file]')[0].files[0];
       var supmaterial = $(workMattersTableIndex + ' .fileUploader input[type=text]').val();
       var eightfieldsId = eightFieldsIds.join(',');

       if (problem == '' || measures == '' || finish == '' || fourforms == '' || diseducation == '' || eightFieldsIds.length == 0 || supmaterial == '') {
           alert("请完整填写信息,并上传支撑材料");
       } else {
           finishDialog(workMattersTableIndex + ' .simpleDialog.addDialog');
           var selfExaminationForm = $('.yangxunForm');
           var formData = new FormData(selfExaminationForm);//通过form元素构造formData对象
           formData.append('problem', problem);
           formData.append('measures', measures);
           formData.append('finish', finish);
           formData.append('fourforms', fourforms);
           formData.append('diseducation', diseducation);
           formData.append('file', file);
           formData.append('userId', userId);
           formData.append('eightfieldsId', eightfieldsId);
           formData.append('userDepartment', userDepartment);

           $.ajax({
               url: mmssm_url + "selfexamination/insert",
               type: "POST",
               processData: false,
               contentType: false,//上传formdata的时候需要设置这两个属性
               dataType: "JSON",
               data: formData,
               success: function (data) {
                   eightFieldsIds.splice(0);
                   if (data != -1) {
                       resultDialog(true, workMattersTableIndex + ' .simpleDialog.addDialog', function () {});
                   } else {
                       resultDialog(false, workMattersTableIndex + ' .simpleDialog.addDialog', function () {});
                   }
               },
               error: function (error) {
                   resultDialog(false, workMattersTableIndex + ' .simpleDialog.addDialog', function () {});
               }
           });
       }
    });



    $(".fileUploader input[type=file]").change(function() {
        $(this).parents(".uploader").find(".filename").val($(this).val());
    });


    $('.searchbox').focus(function () {
        var selectedIndex = $(workMattersTableIndex + ' .searchSelect').get(0).selectedIndex;
        switch (selectedIndex) {
            case 0:
                $(workMattersTableIndex + ' .searchboxIndicator ul li').remove();
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="1">2017年网公司党组巡视</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="2">2018年省公司对茂名供电局“机动式”巡察</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="3">五个专项治理、五个专项行动</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="4">其它巡视巡察</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="5">扫雷行动</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="6">红包专项治理</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="7">正风反腐三年行动</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li data-index="8">形式主义、官僚主义专项治理</li>'));
                break;
            case 3:
                $(workMattersTableIndex + ' .searchboxIndicator ul li').remove();
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>基建领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>物流领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>市场营销领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>办公领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>财务领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>监察领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>企管领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>人资领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>党建人事领域</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>计划发展领域</li>'));
                break;
            case 4:
                $(workMattersTableIndex + ' .searchboxIndicator ul li').remove();
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>基建部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>物流服务中心</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>市场营销部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>办公室</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>财务部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>计划发展部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>监察部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>审计部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>党建人事部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>人力资源部</li>'));
                $(workMattersTableIndex + ' .searchboxIndicator ul').append($('<li>党建人事部</li>'));
                break;
            default:
                return;
        }
        $('.searchboxIndicator ul li').click(function () {
            $(workMattersTableIndex + ' .searchbox').data('index', $(this).data('index'));
            $(workMattersTableIndex + ' .searchbox').val($(this).text());
            $(workMattersTableIndex + ' .searchboxIndicator').animate({height: 'hide'}, 100);
        });
        $(workMattersTableIndex + ' .searchboxIndicator').outerWidth($(this).outerWidth());
        $(workMattersTableIndex + ' .searchboxIndicator').animate({height: 'show'}, 100);
    });

    $('.searchBtn').click(function (event) {
        event.preventDefault();//阻止按钮事件冒泡，避免调用form的submit事件
        var selectedIndex = $(workMattersTableIndex + ' .searchSelect').get(0).selectedIndex;
        var unknownData = $(workMattersTableIndex + ' .searchbox').val();
        if (unknownData == '' || unknownData == null) {
            alert("请填写要查询的内容");
        }
        var searchUrl = '';
        //查询工单时默认增加用户id字段作为查询条件，因为每个用户只能查看属于自己的工单;20181213:新需求，可以查询另外用户的工单，但是要别人的工单只能部分开放
        var searchData = {};
        switch (selectedIndex) {
            case 0:
                var index = $(workMattersTableIndex + ' .searchbox').data('index');
                searchData.eightfields = [{'eightFieldsIndex': index}];
                searchUrl = 'selectEf';
                break;
            case 1:
                searchData.eightfields = [{'compareItem': unknownData}];
                searchUrl = 'selectEf';
                break;
            case 2:
                searchData.userName = unknownData;
                searchUrl = 'selectUser';
                break;
            case 3:
                searchData.userDomain = unknownData;
                searchUrl = 'selectUser';
                break;
            case 4:
                searchData.userDepartment = unknownData;
                searchUrl = 'selectUser';
                break;
            default:
                return;
        }
        searchData = JSON.stringify(searchData);//将查询数据转换成json字符串,后端要用@RequestBody接收
        //重新设置表格插件的配置（这里是更改请求内容）
        config.controller = {
            loadData: function() {
                var d = $.Deferred();

                $.ajax({
                    type: "post",
                    contentType: 'application/json;charset=UTF-8',
                    url: mmssm_url + "selfexamination/" + searchUrl,//后端要用@RequestBody接收
                    dataType: "json",
                    data: searchData,
                }).done(function(response) {
                    if (response.length == 0 || response == null) {
                        response = {};
                    } else {
                        response = resolveTableData(response);
                        console.log(response);
                    }
                    d.resolve(response);
                }).fail(function () {
                    console.log("Table can't get search data.selectEf");
                });
                return d.promise();
            },
            deleteItem: function (rowData) {
                // deleteSelfexamination(rowData);
            }
        };
        $(workMattersTableIndex + ' .jsgrid').jsGrid(config);
    });

    $('.searchSelect').change(function () {
        $(workMattersTableIndex + ' .searchbox').val('');
        $(workMattersTableIndex + ' .searchboxIndicator').animate({height: 'hide'}, 100);
    });
});